// CountdownFlipCard.js
import React, { useState, useEffect, useRef } from 'react';
import './CountdownFlipCard.css';
/**
 * 倒计时组件
 * @param {number} initialSeconds - 初始秒数
 * @param {function} onEnd - 倒计时结束回调函数
 * @returns {JSX.Element} - 倒计时组件
 */
const CountdownFlipCard = ({ initialSeconds, onEnd }) => {
  // console.log(initialSeconds,"初始秒数");
  const sanitizedSeconds = Math.max(0, initialSeconds*1); // Ensure non-negative seconds
  const [time, setTime] = useState({
    hours: Math.floor(sanitizedSeconds / 3600),
    minutes: Math.floor((sanitizedSeconds % 3600) / 60),
    seconds: sanitizedSeconds % 60,
  });

  const intervalRef = useRef();

  useEffect(() => {
    const updateTimer = () => {
      setTime(prevTime => {
        const totalSeconds = prevTime.hours * 3600 + prevTime.minutes * 60 + prevTime.seconds - 1;
        if (totalSeconds < 0) {
          clearInterval(intervalRef.current);
          onEnd();
          return prevTime;
        }
        return {
          hours: Math.floor(totalSeconds / 3600),
          minutes: Math.floor((totalSeconds % 3600) / 60),
          seconds: totalSeconds % 60,
        };
      });
    };

    // Clear any existing interval
    clearInterval(intervalRef.current);

    // Set new interval
    intervalRef.current = setInterval(updateTimer, 1000);

    // Initialize time state based on new initialSeconds
    setTime({
      hours: Math.floor(sanitizedSeconds / 3600),
      minutes: Math.floor((sanitizedSeconds % 3600) / 60),
      seconds: sanitizedSeconds % 60,
    });

    return () => clearInterval(intervalRef.current);
  }, [initialSeconds]);

  return (
    <div className="countdown">
      <FlipCard label="Hours" value={time.hours} />
      <div className='colon'>：</div>
      <FlipCard label="Minutes" value={time.minutes} />
      <div className='colon'>：</div>
      <FlipCard label="Seconds" value={time.seconds} />
    </div>
  );
};

const FlipCard = ({ label, value }) => (
  <div className="flip-card">
    <div className="flip-card-inner">
      <div className="flip-card-front">
        {value.toString().padStart(2, '0')}
      </div>
      <div className="flip-card-back">
        {value.toString().padStart(2, '0')}
      </div>
    </div>
  </div>
);

export default CountdownFlipCard;